/**
 * 请求拦截器，用于在请求头中添加token
 */
import { getCookie, deleteCookie, setCookie, deleteUserInfo } from './cookieUtils';

/**
 * 从localStorage或cookie获取管理员token
 * @returns token字符串或null
 */
export const getToken = (): string | null => {
  // 优先从localStorage获取
  const localToken = localStorage.getItem('admin_token');
  if (localToken) {
    return localToken;
  }

  // 备用从cookie获取
  return getCookie('admin_token');
};

/**
 * 设置管理员token
 * @param token token字符串
 * @param expireDays 过期天数，默认7天
 */
export const setToken = (token: string, expireDays: number = 7): void => {
  // 同时保存到localStorage和cookie
  localStorage.setItem('admin_token', token);
  setCookie('admin_token', token, expireDays);
};

/**
 * 设置请求头的授权信息
 * @param headers 请求头对象
 */
export const setAuthHeader = (headers: Record<string, string>): void => {
  const token = getToken();
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
};

/**
 * 清除token和用户信息，用于登出
 */
export const clearToken = (): void => {
  localStorage.removeItem('admin_token');
  deleteCookie('admin_token');
  deleteUserInfo(); // 同时清除用户信息
};